package com.yanq.liancar.activity;

import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.yanq.liancar.R;
import com.yanq.liancar.base.BaseActivity;
import com.yanq.liancar.url.Config;
import com.yanq.liancar.util.FileProvider7;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

public class ApkDown extends BaseActivity {

    private TextView percent;
    private ProgressBar progressBar;
    private static final int loading = 1;
    private static final int end = 2;
    private String LOADING_SIZE = "loading_size";
    private String CURRENT_FILE = "current_file";
    private Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (null != progressBar) {
                if (msg.what == loading) {
                    int nowSize = msg.getData().getInt(LOADING_SIZE);
                    percent.setText("已下载: " + nowSize + "%");
                }
                if (msg.what == end) {
                    progressBar.setVisibility(View.INVISIBLE);
                    String file = msg.getData().getString(CURRENT_FILE);
                    percent.setText("下载完成,即将安装!");
                    if (file != null) {
                        Intent intent = new Intent(Intent.ACTION_VIEW);
//                        intent.setDataAndType(Uri.fromFile(new File(file)), "application/vnd.android.package-archive");
                        FileProvider7.setIntentDataAndType(ApkDown.this, intent, "application/vnd.android.package-archive", new File(file), true);
                        startActivity(intent);
                    }
                    finish();
                }
            }
        }
    };

    @Override
    public int getContentResId() {
        return R.layout.apk_down;
    }

    public static void start(Context context) {
        Intent intent = new Intent(context, ApkDown.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
        context.startActivity(intent);
    }

    @Override
    public void init() {
        percent = (TextView) findViewById(R.id.percent);
        progressBar = (ProgressBar) findViewById(R.id.progressbar);
        percent.setText("即将下载......");
        progressBar.setVisibility(View.VISIBLE);
        String fullName = Environment.getExternalStorageDirectory().getAbsolutePath() + "/com.wy.tbcbuy/apk/tbcbuy.apk";
        new DownloadAPK(fullName).execute(Config.APK_URL);
    }

    private class DownloadAPK extends AsyncTask<String, Integer, String> {

        private String fullName;

        private DownloadAPK(String fullName) {
            this.fullName = fullName;
        }

        @Override
        protected String doInBackground(String... params) {
            URL url;
            HttpURLConnection conn;
            BufferedInputStream bis = null;
            FileOutputStream fos = null;

            try {
                url = new URL(params[0]);
                conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("GET");
                conn.setConnectTimeout(5000);

                int fileLength = conn.getContentLength();
                bis = new BufferedInputStream(conn.getInputStream());
                File file = new File(fullName);
                if (!file.exists()) {
                    if (!file.getParentFile().exists()) {
                        file.getParentFile().mkdirs();
                    }
                    file.createNewFile();
                }
                fos = new FileOutputStream(file);
                byte data[] = new byte[4 * 1024];
                long total = 0;
                int count;
                while ((count = bis.read(data)) != -1) {
                    total += count;
                    publishProgress((int) (total * 100 / fileLength));
                    fos.write(data, 0, count);
                    fos.flush();
                }
                fos.flush();

            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (fos != null) {
                        fos.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
                try {
                    if (bis != null) {
                        bis.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            return null;
        }

        @Override
        protected void onProgressUpdate(Integer... progress) {
            super.onProgressUpdate(progress);
            int p = progress[0];
            progressBar.setProgress(p);
            Message msg = new Message();
            msg.what = loading;
            Bundle bundle = new Bundle();
            bundle.putInt(LOADING_SIZE, p);
            msg.setData(bundle);
            handler.sendMessage(msg);
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            Message msg = new Message();
            msg.what = end;
            Bundle bundle = new Bundle();
            bundle.putString(CURRENT_FILE, fullName);
            msg.setData(bundle);
            handler.sendMessage(msg);
        }
    }
}